package com.tough.engine;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

import com.tough.engine.scene.Stage;
import com.tough.engine.scene.StageTestPlace;

public class GmCanvas extends Canvas implements Runnable{
	
	public long SLEEP_MS;	
	private Stage stage;
	private long lastMarkTime=0;

	public static byte FPSNum = 0;
	
	public GmCanvas() {
		stage = new StageTestPlace();
		SLEEP_MS = 1000 / GmConst.FPS;
		setFullScreenMode(true);
		
	}
	
	protected void paint(Graphics g) {
		stage.clean(g);
		stage.logic();
		stage.draw(g);
	}
	
	protected void keyPressed(int keyCode) {
		stage.keyPressed(keyCode);
	}
	
	protected void keyReleased(int keyCode) {
		stage.keyReleased(keyCode);
	}
	
	public void run() {
		long start = 0;
		long end = 0;
		int time = 0;
		while (true) {
			start = System.currentTimeMillis();
			GmConst.currentTime = start;
			
			repaint();
			
			end = System.currentTimeMillis();
			time = (int) (end - start);
			try {
				if(time < SLEEP_MS){
					calculateFPS();
					Thread.sleep(SLEEP_MS - time);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void calculateFPS() {
		FPSNum++;
		if(GmConst.currentTime - lastMarkTime > 1000){
			GmConst.FPSNum = FPSNum;
			lastMarkTime = GmConst.currentTime;
			FPSNum = 0;
		}
	}
}
